package com.xiaoxiao.springbootstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxiao.springbootstudy.pojo.Menu;
import com.xiaoxiao.springbootstudy.pojo.vo.MenuVO;
import com.xiaoxiao.springbootstudy.service.MenuService;
import com.xiaoxiao.springbootstudy.mapper.MenuMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author XiaoXiao
* @description 针对表【t_menus】的数据库操作Service实现
* @createDate 2025-05-13 14:45:56
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<MenuVO> getMenus() {
        List<Menu> menus = this.list();
        System.out.println(menus);

        return prepareSubMenus(menus, 0);
    }

    @Override
    public void saveMenusService(Menu newmenu) {
        QueryWrapper<Menu> wrapper=new QueryWrapper<>();
        wrapper.select("max(component) maxv");

        Menu menu = menuMapper.selectOne(wrapper);

        newmenu.setComponent(menu.getMaxv()+1);
        menuMapper.insert(newmenu);
    }


    public List<MenuVO> prepareSubMenus(List<Menu> menus, Integer menuId) {
        List<MenuVO> subMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if(menu.getPid().equals(menuId)){
                MenuVO newMenuVO = new MenuVO();
                BeanUtils.copyProperties(menu, newMenuVO);
                newMenuVO.setChildren(prepareSubMenus(menus, menu.getId()));
                subMenus.add(newMenuVO);
            }
        }

        return subMenus;
    }
}




